package com.diapoclic.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.diapoclic.entitybean.Document;
import com.diapoclic.entitybean.User;
import com.diapoclic.entitydao.DocumentDao;
import com.diapoclic.entitymanager.DocumentManager;
import com.diapoclic.entitymanager.UserManager;
 
 
public class CommonsFileUploadServlet extends HttpServlet {
	
	
	private static final long serialVersionUID = 1L;
	private static final String TMP_DIR_PATH = "/tmp";
	private File tmpDir=new File("tmpDir");
	private File destinationDir =new File("destinationDir");
 
//	public void init(ServletConfig config) throws ServletException {
//		super.init(config);
//		
//    	tmpDir = new File(TMP_DIR_PATH);
//		if(!tmpDir.isDirectory()) {
//			throw new ServletException(TMP_DIR_PATH + " is not a directory");
//		}
//	
//	}
 
	
	protected void doGet (HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
	    System.out.println("début de la méthode doGet");


		request.getRequestDispatcher("addPhotoForm.jsp").forward(request, response);
		
	}	
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
	    response.setContentType("text/plain");
	    System.out.println("début de la méthode doPost");

	    UserManager userMana = new UserManager();
	    User sessionUser = new User();
		DocumentManager documentMana=new DocumentManager();
		Document doc=new Document();
		////////////////////////////////UTILISATION DES COOKIES///////////////////////////

		sessionUser=userMana.getSessionUser(request.getCookies());
    	
  
		////////////////////////////////ENREGISTREMENT DU FICHIER ///////////////////////////

		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		
		//Taille Maximum des fichiers
		fileItemFactory.setSizeThreshold(1*1024*1024*5); //5 MB
		
		//on stocke temporairement la photo dans le dossier /tmp
		fileItemFactory.setRepository(tmpDir);
 
		//on récupère les infos du formulaire
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			
			
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				
				
				if(item.isFormField()) {
					System.out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
				} else {
					//Info sur le fichier uploader
					System.out.println("Field Name = "+item.getFieldName()+
						", File Name = "+item.getName()+
						", Content type = "+item.getContentType()+
						", File Size = "+item.getSize());
					
					// Ajout dans la Bdd
					doc.setNameDoc(item.getName());
					doc.setType(item.getContentType());
					doc.setSize((int)item.getSize());
					doc.setUser(sessionUser);
					doc.setPath("photos/"+sessionUser.getLogin()+"/"+item.getName());

					documentMana.getDocumentDao().addDocument(doc.getNameDoc(), doc.getComment(), doc.getSize(), doc.getType(), doc.getPath(), doc.getUser().getIdUser());
					
					//Stockage du fichier dans le dossier définitif
					
					destinationDir = new File(getServletContext().getRealPath("/photos/"+sessionUser.getLogin()));

					File file = new File(destinationDir,item.getName());
					item.write(file);
				}
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
		
		request.getRequestDispatcher("album.jsp").forward(request, response);

	}
 
	
	
}